package shiyan5;

import Calculate.Judge;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

public class SocketServer3 {
    public static void main(String[] args) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, ClassNotFoundException {
        //1.建立一个服务器Socket(ServerSocket)绑定指定端口
        ServerSocket serverSocket=new ServerSocket(8800);
        //2.使用accept()方法阻止等待监听，获得新连接
        Socket socket=serverSocket.accept();
        //3.获得输入流
        InputStream inputStream=socket.getInputStream();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
        //获得输出流
        OutputStream outputStream=socket.getOutputStream();
        PrintWriter printWriter=new PrintWriter(outputStream);
        //4.读取用户输入信息
        byte[] ctext = inputStream.readAllBytes();
        System.out.print("我是20172305谭鑫服务器，我接收到的内容是：");
        for(int a=0;a<ctext.length;a++) {
            System.out.print(ctext[a] + " ");
        }
        System.out.println();

        FileInputStream f=new FileInputStream("key1.dat");
        ObjectInputStream b=new ObjectInputStream(f);
        Key k=(Key)b.readObject( );

        Cipher cp=Cipher.getInstance("shiyan5.AES");
        cp.init(Cipher.DECRYPT_MODE, k);
        byte []ptext=cp.doFinal(ctext);
        System.out.print("服务器解密后的内容是：");
        for(int a=0;a<ptext.length;a++) {
            System.out.print(ptext[a] + " ");
        }
        System.out.println();
        String p=new String(ptext,"UTF8");

        //给客户一个响应
        Judge judge = new Judge();
        String reply = judge.answer(p);
        System.out.println("服务器运算结果：" + reply);
        printWriter.write(reply);
        printWriter.flush();
        //5.关闭资源
        printWriter.close();
        outputStream.close();
        bufferedReader.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}
